package com.ddwl.gate.service;

import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.RedisKey;
import com.ddwl.common.service.RedisService;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.gate.BaiduVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author Fu Zhaohui
 * @date 2017/1/3
 */
@Slf4j
@Service
public class VoiceService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private RestTemplate restTemplate;


    public void scheduleToken() {
//        Map<String, String> entryMap = redisService.getHashOps().entries(RedisKey.VOICE_BAIDU_ACCOUNT.getKey());
//        if (entryMap != null && !entryMap.isEmpty()) {
////            String appId = entryMap.get("app_id");
//
//        }
//
//        entryMap = redisService.getHashOps().entries(RedisKey.VOICE_ALIYUN_KEY.getKey());
//        if (entryMap != null && entryMap.isEmpty()) {
//
//        }
    }


    public String getToken() {
        Map<String, String> entryMap = redisService.getHashOps().entries(RedisKey.VOICE_BAIDU_ACCOUNT.getKey());
        if (entryMap != null && !entryMap.isEmpty()) {
            String expiresIn = entryMap.get("expires_in");
            if (StringUtils.hasText(expiresIn) && System.currentTimeMillis() < Long.parseLong(expiresIn)) {
                return entryMap.get("access_token");
            }
            return getBaiduToken(entryMap.get("api_key"), entryMap.get("secret_key"), entryMap.get("refresh_token"));
        }
        return null;
    }


    private String getBaiduToken(String apiKey, String secretKey, String refreshToken) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity entity = new HttpEntity(headers);
        StringBuilder sb = new StringBuilder("https://openapi.baidu.com/oauth/2.0/token");
        BaiduVo resp;
        if (StringUtils.hasText(refreshToken)) {
            sb.append("?grant_type=refresh_token&refresh_token={refreshToken}&client_id={apiKey}&client_secret={secretKey}");
            resp = restTemplate.postForObject(sb.toString(), entity, BaiduVo.class, refreshToken, apiKey, secretKey);
        } else {
            sb.append("?grant_type=client_credentials&client_id={apiKey}&client_secret={secretKey}");
            resp = restTemplate.postForObject(sb.toString(), entity, BaiduVo.class, apiKey, secretKey);
        }

        log.info("########### " + JSON.toJSONString(resp));
        redisService.getHashOps().put(RedisKey.VOICE_BAIDU_ACCOUNT.getKey(), "access_token", resp.getAccess_token());
        redisService.getHashOps().put(RedisKey.VOICE_BAIDU_ACCOUNT.getKey(), "refresh_token", resp.getRefresh_token());
        redisService.getHashOps().put(RedisKey.VOICE_BAIDU_ACCOUNT.getKey(), "session_key", resp.getSession_key());
        redisService.getHashOps().put(RedisKey.VOICE_BAIDU_ACCOUNT.getKey(), "session_secret", resp.getSession_secret());
        redisService.getHashOps().put(RedisKey.VOICE_BAIDU_ACCOUNT.getKey(), "scope", resp.getScope());
        redisService.getHashOps().put(RedisKey.VOICE_BAIDU_ACCOUNT.getKey(), "expires_in", (System.currentTimeMillis() + resp.getExpires_in() * 1000) + "");
        redisService.getHashOps().put(RedisKey.VOICE_BAIDU_ACCOUNT.getKey(), "timestamp", DateUtil.getCurrDate(DateUtil.DATE_TIME_FORMAT));
        return resp.getAccess_token();
    }
}
